<?php
session_start();
require("../includes/dbInfo.php");

if (isset($_GET['productID'])) {
    if( $_GET['productID'] == "all"){
        deleteAll();
    }
   else if( (int)$_GET['productID'] > 0 ) {
       $productID = (int)$_GET['productID'];
       deleteOne($productID);
    }
}    
// invalid input just go back to list products
else{
    header('location: listProducts.php');
}


function deleteAll(){
    $sql = "TRUNCATE TABLE products";
    mysql_query($sql) or die(mysql_error());
    header('location: listProducts.php');
}

// This removes one product at a time
function deleteOne($productID) {
    
    // If the product has been ordered then we cannot delete it
    $sql = "SELECT COUNT(*) from itemsOrdered where productID = '$productID'";
    $count = mysql_query($sql) or die(mysql_error()); 
    $count = mysql_fetch_row($count);

    if( $count[0] > 0 ) {
       header("location: listProducts.php?deleteError=$productID");
    }
    else {
        // remove the product from database;
        $sql = "DELETE FROM products WHERE productID = $productID";
        mysql_query($sql) or die(mysql_error()); 
        header("location: listProducts.php?deleteSuccess=1");
    }

}
?>